<script setup lang="jsx">
import { ref, onMounted, watch } from 'vue'
// import { result } from './constant'
import AMapLoader from '@amap/amap-jsapi-loader'
import { pageHandle } from '@/api/common'

let placeSearch = null
let geocoder = null
let auto = null
const loading = ref(false)
const position = ref([])
const result = ref([])
const addressInfo = ref({})


const getLocation = () => {
  // eslint-disable-next-line no-undef
  return new Promise((resolve) => {
    AMap.plugin('AMap.Geolocation', function () {
      const geolocation = new AMap.Geolocation({
        // 是否使用高精度定位，默认：true
        enableHighAccuracy: true,
        // 设置定位超时时间，默认：无穷大
        timeout: 10000,
      })
      //进行IP城市查询
      geolocation.getCityInfo(function (status, result) {
        if (status == 'complete') {
          console.log('geolocation.getCityInfo-complete', result)
          position.value = result?.center || []
        } else {
          position.value = [104.923767, 30.574471]
          console.log('geolocation.getCityInfo-error', result)
          // getLngLatLocation()
        }
        resolve()
      })
      //获取用户当前的精确位置信息(经纬度)
      // geolocation.getCurrentPosition(function (status, result) {
      //   if (status == 'complete') {
      //     console.log('geolocation.getCurrentPosition-complete', result)
      //   } else {
      //     console.log('geolocation.getCurrentPosition-error', result)
      //     getLngLatLocation()
      //   }
      // })
    })
  })
}
const getLngLatLocation = () => {
  //只获取城市级别的定位信息
  AMap.plugin('AMap.CitySearch', function () {
    const citySearch = new AMap.CitySearch()
    citySearch.getLocalCity(function (status, result) {
      if (status === 'complete' && result.info === 'OK') {
        // 查询成功，result即为当前所在城市信息
        console.log('通过ip获取当前城市：', result)
        self.cityName = result.city
        self.cityCode = result.adcode
        var lnglat = result.rectangle.split(';')[0].split(',')
        self.longitude = lnglat[0]
        self.latitude = lnglat[1]
        //逆向地理编码查询地理位置详细信息
        AMap.plugin('AMap.Geocoder', function () {
          var geocoder = new AMap.Geocoder({
            // city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
            city: result.adcode,
          })
          var lnglat = result.rectangle.split(';')[0].split(',')
          geocoder.getAddress(lnglat, function (status, data) {
            if (status === 'complete' && data.info === 'OK') {
              // result为对应的地理位置详细信息
              console.log(data, '地理位置')
            }
          })
        })
      }
    })
  })
}
const initAMap = () => {
  return new Promise((resolve) => {
    window._AMapSecurityConfig = {
      securityJsCode: '597c21d68d8bd4a6a3243c1be71d2593',
    }
    AMapLoader.load({
      key: '61ef7ff0b3c20441da992998eddd18ff', // 申请好的Web端开发者Key，首次调用 load 时必填
      version: '1.4.15', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
      plugins: [
        'AMap.Geolocation',
        'AMap.CitySearch',
        'AMap.Autocomplete',
        'AMap.Geocoder',
        'AMap.DistrictSearch',
        'AMap.PlaceSearch',
      ], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      AMapUI: {
        version: '1.1',
        plugins: ['control/BasicControl'],
      },
    })
      .then(AMap => {
        placeSearch = new AMap.PlaceSearch()
        geocoder = new AMap.Geocoder()
        //输入提示
        auto = new AMap.Autocomplete({
          input: 'tipinput',
          datatype: 'all',
        })
        auto.on('select', e => {
          const poi = e?.poi || {}
          // const location = e?.poi?.location?.toString()
          const lat = e?.poi?.location?.getLat()
          const lng = e?.poi?.location?.getLng()
          const name = e?.poi?.name
          console.log('Autocomplete-complete', e)

          if (lat && lng) {
            position.value = [lng, lat]
            return
          }

          if (name && !lat && !lng) {
            placeSearch.search(e?.poi?.name, (status, result) => {
              const location = result?.poiList?.pois?.find(item => item?.location)
              console.log('placeSearch-complete', location)

              const lat = location?.location?.getLat()
              const lng = location?.location?.getLng()
              if (lat && lng) {
                position.value = [lng, lat]
              }
            })
          }
        })
        resolve()
      })
      .catch(e => {
        console.log(e)
        resolve()
      })
  })
}


function isWechat() {
  return window.navigator.userAgent.indexOf("MicroMessenger") !== -1;
}

const handleAddress = (item) => {
  console.log(isWechat(), 'isWechat()');
  if (isWechat()) {
    alert(`
      暂不支持在微信在打开高德地图
      您可以点击右上角"在浏览器打开"
      或者使用三方浏览器打开
      `)
    return;
  }
  // const { adcode, formattedAddress } = addressInfo.value || {}
  // const [lng, lat] = position.value || []
  const { longitude: lng, latitude: lat, name: formattedAddress } = item || {}
  const url = `amapuri://route/plan/?dlat=${lat}&dlon=${lng}&dname=${formattedAddress}&dev=0&t=0&src=NEARBY_BRANCH&coordinate=gaode&callnative=1`;
  console.log('url', url, item);
  window.location.href = url
  // window.open(url)
}



const getList = async () => {
  const [lng, lat] = position.value || []
  if (!lng || !lat) return
  try {
    const data = await pageHandle({ lng, lat })
    result.value = data || [];
  } catch (error) {
    console.error(error)
    result.value = [];
  }
}

const init = async () => {
  try {
    loading.value = true;
    await initAMap()
    await getLocation()
  } catch (error) {
    console.log('出错了');
  }
  loading.value = false;
}
watch(
  () => position.value,
  location => {
    if (location?.length === 2) {
      geocoder.getAddress(location, function (status, data) {
        if (status === 'complete' && data.info === 'OK') {
          // result为对应的地理位置详细信息
          addressInfo.value = {
            formattedAddress: data?.regeocode?.formattedAddress,
            adcode: data?.regeocode?.addressComponent?.adcode,
          }
          getList()
        }
      })
    }
  },
)
onMounted(() => {
  init()
})
</script>

<template>
  <div class="nearby-branch-wrapper" id="nearby-branch-wrapper">
    <div class="info">
      <span class="input-item-text">请输入关键字搜索</span>
      <input class="input-item" autocomplete="off" id="tipinput" type="text" />
    </div>
    <div class="nearby-branch-container">
      <div class="nearby-branch-content" v-for="item in result" :key="item.id">
        <div class="header">
          <img :src="`https://www.tfxysc.com/${item?.log}`" alt="" v-if="item?.log" />
          <div class="right">
            <div class="name">{{ item?.name }}</div>
            <div class="services">{{ item?.services?.join('，') }}</div>
          </div>
        </div>
        <div class="item servicetime">
          <div class="label">服务时间:</div>
          <div class="value">{{ item?.servicetime }}</div>
        </div>
        <div class="item lineup_desc">
          <div class="label">拥挤程度:</div>
          <div class="value" :style="{ color: item?.lineup_color }">
            {{ item?.lineup_desc }}
          </div>
        </div>
        <div class="item distance">
          <div class="label">离您距离:</div>
          <div class="value">{{ item?.distance || 0 }}公里</div>
        </div>
        <div class="line"></div>
        <div class="address" v-if="item?.address" @click="handleAddress(item)">
          
          <span class="text">{{ item?.address }}</span>
          <img class="location" src="@/assets/location.svg" />
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="less">
.info {
  padding: 0rem 0.12rem;
  border-radius: 0.02rem;
  background-color: white;
  border-width: 0;
  height: 0.64rem;
  box-shadow: 0 2px 6px 0 rgba(114, 124, 245, 0.5);
  display: flex;
  align-items: center;
  font-size: 0.14rem;

  .input-item-text {
    margin-right: 0.08rem;
    flex-shrink: 0;
    font-size: 0.14rem;
  }

  .input-item {
    font-size: 0.14rem;
    height: 0.32rem;
    line-height: 0.32rem;
    flex: 1;
    flex-grow: 1;
    border: 1px solid #cdd2da;
    padding: 0 0.08rem;
    outline: none;
    border-radius: 0.04rem;

    &:focus {
      border-color: #059e84;
    }
  }
}

.nearby-branch-wrapper {
  height: 100vh;
  overflow: hidden;

  .nearby-branch-container {
    overflow: auto;
    height: calc(100vh - 0.64rem);
    padding: 0 0.12rem;
  }

  .nearby-branch-content {
    padding: 0.12rem;
    border: 1px solid var(--vt-c-white-mute, #f2f2f2);
    margin-top: 0.12rem;
    border-radius: 0.12rem;
    overflow: hidden;

    .name {
      font-size: 0.16rem;
    }

    .services {
      font-size: 0.12rem;
      background-color: #ecf5ff;
      color: #409eff;
      border: 1px solid #d9ecff;
      padding: 0.02rem;
      border-radius: 0.02rem;
      margin-top: 0.08rem;
      display: inline-flex;
      align-items: center;
    }

    .header {
      display: flex;
      align-items: center;
      .right {
        flex: 1;
        width: 0;
      }
      img {
        width: 0.4rem;
        height: 0.4rem;
        border-radius: 50%;
        margin-right: 0.08rem;
      }
    }

    .item {
      margin-top: 0.08rem;
      font-size: 0.13rem;
      display: flex;
      align-items: flex-start;

      .label {
        width: 0.65rem;
        flex-shrink: 0;
      }

      .value {
        flex: 1;
      }
    }

    .line {
      height: 1px;
      margin: 0.12rem 0;
      background-color: var(--vt-c-white-mute, #f2f2f2);
    }

    .address {
      font-size: 0.13rem;
      display: flex;
      align-items: center;
      cursor: pointer;

      .text {
        flex: 1;
      }

      .location {
        width: 0.32rem;
        flex-grow: 0;
        flex-shrink: 0;
        margin-right: 0.04rem;
      }
    }
  }
}
</style>
